#!/usr/bin/env python
# -*- coding: utf-8 -*-

import subprocess
from tksite_http import get_auth_token
import getopt
from sys import argv, exit
import ConfigParser as configparser

# for Python3.6
# import configparser

config_file_path = 'assets/config.ini'
cf = configparser.ConfigParser()
cf.read(config_file_path)
server_host = cf.get('auth', 'server_host')
server_port = cf.get('auth', 'server_port')
server_base_url = 'http://' + server_host + ':' + server_port
authorization_header = "TK-Authorization"


def send(url=None, params=None, method='', concurrent=10, repetitions=10):
    if method == 'POST':
        cmd = 'siege "{}{} {} {}" -c {} -r {} --header "Content-Type: application/json" --header "{}: {}"'.format(
            server_base_url, url, method, params,
            concurrent,
            repetitions, authorization_header,
            get_auth_token())
    else:
        cmd = 'siege "{}{}?{}" -c {} -r {} --header "Content-Type: application/json" --header "{}: {}"'.format(
            server_base_url, url, params,
            concurrent,
            repetitions, authorization_header,
            get_auth_token())
    print (cmd)
    out = subprocess.check_output(cmd, shell=True)
    print(out)


def post(url=None, parm=None, concurrent=10, repetitions=10):
    send(url, parm, 'POST', concurrent, repetitions)


def get(url=None, parm=None, concurrent=10, repetitions=10):
    send(url, parm, 'GET', concurrent, repetitions)


def test():
    get('/user/list', "page=1&rows=10")
    print("=====================")
    post('/menu/preview')


def usage():
    print("""
参数说明:
    --url: 目标测试的请求的地址
    --parm: 请求参数
    --concurrent: 并发数
    --repetitions: 每个并发重复请求数
    --method: 请求方法，目前支持post或者get(不填写默认get)
    --test: 运行自检测试命令，不支持其他参数
    
命令参考:
    python tksite_parallel_http_requests.py --url "/user/list" --parm "page=1&rows=10" -c 10 -r 10
    """)


if __name__ == '__main__':
    if len(argv[1:]) == 0:
        usage()
        exit()

    opts, args = getopt.getopt(argv[1:], "hu:",
                               ["help", "test", "method=", "url=", "parm=", "concurrent=", "repetitions=", "test="])

    r_method = 'get'
    r_concurrent = 50
    r_repetitions = 10
    r_parm_string = '1=1'
    r_url = None

    for name, value in opts:
        if name in ['-u', '--url']:
            r_url = value
        elif name in ['-p', '--parm']:
            r_parm_string = value
        elif name in ['-m', '--method']:
            r_method = value
        elif name in ['-c', '--concurrent']:
            r_concurrent = value
        elif name in ['-r', '--repetitions']:
            r_repetitions = value
        elif name in ['-t', '--test']:
            test()
            exit()
        elif name in ['-h', '--help']:
            usage()
            exit()

    if r_url is None:
        print('url cant be empty!')
        exit()

    if r_method == 'get':
        get(r_url, r_parm_string, r_concurrent, r_repetitions)
    elif r_method == 'post':
        post(r_url, r_parm_string, r_concurrent, r_repetitions)
    else:
        print('unsupported http method yet!')
        exit()
